package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.list.client.ListFeignClient;
import com.atguigu.gmall.list.model.SearchAttr;
import com.atguigu.gmall.list.model.SearchParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: atguigu
 * @create: 2023-09-11 15:44
 */
@Controller
public class ListHtmlController {


    @Autowired
    private ListFeignClient listFeignClient;

    /**
     * 搜索页面渲染
     *
     * @param model
     * @param searchParam
     * @return
     */
    @GetMapping("/list.html")
    public String listHtml(Model model, SearchParam searchParam) {
        //1.远程调用搜索服务进行检索
        Result<Map> result = listFeignClient.search(searchParam);
        model.addAllAttributes(result.getData());
        //2.用户提交请求参数 ${searchParam}  以下所有用于回显参数本应该在前端进行处理
        model.addAttribute("searchParam", searchParam);
        //3.搜索条件完整链接 ${urlParam}
        model.addAttribute("urlParam", this.makeUrlParam(searchParam));
        //4.品牌面包屑 ${trademarkParam}
        model.addAttribute("trademarkParam", this.makeTrademarkParam(searchParam.getTrademark()));
        //5.选中平台属性 ${propsParamList}
        model.addAttribute("propsParamList", this.makePropsParamList(searchParam.getProps()));
        //6.排序效果${orderMap}
        model.addAttribute("orderMap", this.makeOrderMap(searchParam.getOrder()));
        return "/list/index";
    }


    /**
     * 用于回显排序效果
     *
     * @param order
     * @return
     */
    private Map<String, String> makeOrderMap(String order) {
        //默认按照相关度得分排序（使用ES默认排序即可）
        Map<String, String> orderMap = new HashMap<>();
        if (StringUtils.isBlank(order)) {
            orderMap.put("type", "3");
            orderMap.put("sort", "asc");
            return orderMap;
        }
        //用户选择排序规则  1:asc
        String[] split = order.split(":");
        if (split != null && split.length == 2) {
            orderMap.put("type", split[0]);
            orderMap.put("sort", split[1]);
            return orderMap;
        }
        return null;
    }

    /**
     * 用于回显用户选中平台属性面包屑
     *
     * @param props
     * @return
     */
    private List<SearchAttr> makePropsParamList(String[] props) {
        if (props != null && props.length > 0) {
            List<String> propStringList = Arrays.asList(props);
            List<SearchAttr> searchAttrList = propStringList.stream().map(propsStr -> {
                // 平台属性ID：平台属性值：平台属性名称
                String[] split = propsStr.split(":");
                SearchAttr searchAttr = new SearchAttr();
                if (split != null && split.length == 3) {
                    searchAttr.setAttrId(Long.valueOf(split[0]));
                    searchAttr.setAttrValue(split[1]);
                    searchAttr.setAttrName(split[2]);
                }
                return searchAttr;
            }).collect(Collectors.toList());
            return searchAttrList;
        }
        return null;
    }


    /**
     * 用于回显用户选中品牌面包屑   品牌: 用户选择品牌名称
     *
     * @param trademark
     * @return
     */
    private String makeTrademarkParam(String trademark) {
        if (StringUtils.isNotBlank(trademark)) {
            String[] split = trademark.split(":");
            if (split != null && split.length == 2) {
                return "品牌：" + split[1];
            }
        }
        return null;
    }

    /**
     * 用户回显地址栏中请求 包含搜索条件完整链接 ${urlParam}
     *
     * @param searchParam
     * @return
     */
    private String makeUrlParam(SearchParam searchParam) {
        //声明基本搜索页面地址
        StringBuilder stringBuilder = new StringBuilder("/list.html?");
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            stringBuilder.append("&keyword=" + searchParam.getKeyword());
        }
        if (StringUtils.isNotBlank(searchParam.getTrademark())) {
            stringBuilder.append("&trademark=" + searchParam.getTrademark());
        }
        if (searchParam.getCategory1Id() != null) {
            stringBuilder.append("&category1Id=" + searchParam.getCategory1Id());
        }
        if (searchParam.getCategory2Id() != null) {
            stringBuilder.append("&category2Id=" + searchParam.getCategory2Id());
        }
        if (searchParam.getCategory3Id() != null) {
            stringBuilder.append("&category3Id=" + searchParam.getCategory3Id());
        }
        String[] props = searchParam.getProps();
        if (props != null && props.length > 0) {
            for (String prop : props) {
                stringBuilder.append("&props=").append(prop);
            }
        }
        return stringBuilder.toString();
    }
}
